<?php

namespace App\Model;

use App\Repository\Sys\Db;
use App\Repository\Common\ConstTable;
use App\Repository\Sys\JsonRespose;
use App\Repository\Sys\Str;

class TimeBlockTable
{
    use Db;
    static private $table = 'time_block';


    /**
     *
     * 获取指定场次时间 价格和锁
     * @param $day | 哪一天
     * @param $field_id | 场地
     * @param $start_time | 开始几点
     * @param $end_time |到几点
     * @return array
     */
    static function getBlockStatus($day, $field_id, $start_time, $end_time)
    {
        // 1.创建一个方法接收一个原始数据(具体的时间段)  返回是否有锁和价格
        // 2.首先查找 数据库是否有 生成的数据 如果有 价格可 从里面确认   如果没有 价格从通用价格设置表取
        // 3.如果数据库有   是否锁定也从 数据判断   如果没有 从lock设置表取


        $field = FieldTable::ORM()->where('id', $field_id)->first();
        //两处联动
        $res = TimeBlockTable::ORM()->where('field_id', $field_id)->where('day', $day)->where('start_time', $start_time)->first();

        $data = ['lock' => self::checkLock($field_id, $day, $start_time, $end_time), 'price' => '0', 'order_id' => 0, 'start_time' => date('H:i', $start_time), 'end_time' => date('H:i', $end_time), '$field_id' => $field_id, '$start_time' => $start_time, '$end_time' => $end_time];

        if ($res) {
            if ($data['lock'] == null) {
                $data['lock'] = self::checkLock($field_id, $day, $start_time, $end_time);
            } else {
                $data['lock'] = ($data['lock'] or $res->lock) ? 1 : 0;
            }
            $data['order_id'] = $res->order_id;
            if ($res->price == null) {
                $data['price'] = self::getPrice($field->storefront_id, $field->type, $start_time, $end_time, $day);
            } else {
                $data['price'] = $res->price;
            }
        } else {

            $data['lock'] = self::checkLock($field_id, $day, $start_time, $end_time);
            $data['price'] = self::getPrice($field->storefront_id, $field->type, $start_time, $end_time, $day);
            $data['order_id'] = 0;
        }

        $data['status'] = FieldTable::getFieldStatus($data['order_id'], $data['lock']);


        return $data;
    }


    /**
     * 检查是否有锁
     * @param $field_id
     * @param $day
     * @param $start_time
     * @param $end_time
     * @return int
     */
    static public function checkLock($field_id, $day, $start_time, $end_time)
    {
        //取出所有配置

        $lock_res = LockSetTable::ORM()->where('field_id', $field_id)->where('start_time', $start_time)->where('end_time', $end_time)->get();

        $lock = 0;
        foreach ($lock_res as $v) {
            //判断是否在时间内
            if ($v->lock_start_time <= $day and $v->lock_end_time >= $day) {
                //判断当前时间是否符合 配置
                //每周
                if ($v->rep_model == 1) {
                    //N	ISO-8601 格式数字表示的星期中的第几天（PHP 5.1.0 新加）	1（表示星期一）到 7（表示星期天）
                    if (date('N', $day) == $v->set_value) {
                        $lock = 1;
                        break;
                    }
                }
                //每月
                if ($v->rep_model == 2) {
                    //j	月份中的第几天，没有前导零	1 到 31
                    if (date('j', $day) == $v->set_value) {
                        $lock = 1;
                        break;
                    }
                }
            } else {
                continue;
            }
        }

        return $lock;
    }

    //获得价格
    static public function getPrice($store_id, $type, $start_time, $end_time, $day = '')
    {
        $def_price_res = false;

        //通过时间区分了方案几

        if ($day) {
            $def_price_res = PriceSetTempTable::ORM()->where('start_time', $start_time)->where('end_time', $end_time)->where('storefront_id', $store_id)->where('type', $type
            )->where('day', $day)->first();
        }


        if (!$def_price_res) {
            $def_price_res = PriceSetTable::ORM()->where('start_time', $start_time)->where('end_time', $end_time)->where('storefront_id', $store_id)->where('type', $type
            )->first();
        }


        if (!$def_price_res) {  //理论上不会出现 ,添加或修改的时候已经初始化

            // 如果不存在 是否需要自动初始化一个价格
//            foreach (ConstTable::DAY_TOTAL_BLOCK_LIST as $v) {
//                PriceSetTable::ORM()->insert([
//                    'start_time' => $v['start_time'],
//                    'end_time' => $v['end_time'],
//                    'storefront_id' => $store_id,
//                    'type' => $type,
//                    'price' => 0.02,//  临时价格
//
//                ]);
//            }
            \Log::error("没有设置设个时间段的价格,不应该出现此错误,严重!!!");
            // 临时
            return 0;
        }
        return $def_price_res->price;
    }

    //判断订场率
    static public function getPercent($field_id, $day)
    {
        $time_list = TimeBlockTable::getFieldTimeList($field_id);
        $count = self::ORM()->where('field_id', $field_id)->where('day', $day)->where('order_id', '!=', 0)->count();
        return (int)(($count / count($time_list)) * 100);
    }

    //返回那种时间方案,目前只有3中,  3是指的全部,并且排好顺序的
    static public function getTimeList($key = 3)
    {
        if ($key == 1) {
            return ConstTable::DAY_TOTAL_BLOCK_LIST[1];
        }
        if ($key == 2) {
            return ConstTable::DAY_TOTAL_BLOCK_LIST[2];
        }
        $time_list = array_merge(ConstTable::DAY_TOTAL_BLOCK_LIST[1], ConstTable::DAY_TOTAL_BLOCK_LIST[2]);
        $sort_arr = [];
        foreach ($time_list as $v) {
            $sort_arr[] = $v['start_time'];
        }
        array_multisort($sort_arr, SORT_ASC, $time_list);
        return $time_list;
    }

    /**
     * 返回场地的时间方案
     * @param $field_id
     * @param int $time
     * @return array
     */
    static public function getFieldTimeList($field_id, $time = 0)
    {
        if (!$time) {
            $time = time();
        }
        $field_res = FieldTable::ORM()->where('id', $field_id)->first();

        if (!$field_res->next_program_time) {
            return TimeBlockTable::getTimeList($field_res->program);
        } else {
            //判断时间是否到了, 如果到了,更新最新的方案，并置空设置
            if ($field_res->next_program_time <= time()) {
                FieldTable::ORM()->where('id', $field_id)->update([
                    'program' => $field_res->next_program,
                    'next_program' => null,
                    'next_program_time' => 0
                ]);
            }

            if ($field_res->next_program_time <= $time) {
                return TimeBlockTable::getTimeList($field_res->next_program);
            } else {
                return TimeBlockTable::getTimeList($field_res->program);
            }
        }
    }


    static public function getProgramText($program)
    {

        if ($program == 1) {
            $program = '一';
        } else {
            $program = '二';
        }
        $time_list = self::getTimeList($program);

        return "规则{$program} " . date('H:i', $time_list[0]['start_time']);
    }


}